/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package niseeServlet.niseeAdmin;

import niseeEntity.NiseeUser;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Bing
 */
public class UserController {

    private EntityManagerFactory emf;

    private EntityManager getEntityManager() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("NiSeeFinalPU");
        }
        return emf.createEntityManager();
    }

    public NiseeUser[] getNiseeAdmin() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select c from NiseeUser as c");
            return (NiseeUser[]) q.getResultList().toArray(new NiseeUser[0]);
        } finally {
            em.close();
        }
    }

    public boolean addAdmin(NiseeUser admin) {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(admin);
            em.getTransaction().commit();
        } finally {
            em.close();
            return false;
        }
    }

    public boolean removeUser(NiseeUser admin) {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            NiseeUser userx = em.find(NiseeUser.class, admin.getUserUSERNAME());
            em.remove(userx);
            em.getTransaction().commit();
        } finally {
            em.close();
            return false;
        }
    }
    public boolean removeUser(String username) {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            NiseeUser userx = em.find(NiseeUser.class, username);
            em.remove(userx);
            em.getTransaction().commit();
        } finally {
            em.close();
            return false;
        }
    }

    public boolean updateAdmin(NiseeUser admin) {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            NiseeUser userx = em.find(NiseeUser.class, admin.getUserUSERNAME());
            userx.setUserEMAIL(admin.getUserEMAIL());
            userx.setUserFAMILYNAME(admin.getUserFAMILYNAME());
            userx.setUserFIRSTNAME(admin.getUserFIRSTNAME());
            userx.setUserPASSWORD(admin.getUserPASSWORD());
            userx.setUserPRIVILEGES(admin.getUserPRIVILEGES());
            em.getTransaction().commit();
        } finally {
            em.close();
            return false;
        }
    }
}